define(['./../initial', './loadProjectMap', './mapInstance', './../model/PublicMap', './../model/project', './viewMode'], function() {
    var app = angular.module('App.home');
    app.factory('loadMap', ['$q', 'loadProjectMap', 'mapInstance', '$rootScope', 'toggleSideBar', 'PublicMap', 'viewMode', 'prjStatusChartModalHelper', 'Project',
        function($q, loadProjectMap, mapInstance, $rootScope, toggleSideBar, PublicMap, viewMode, prjStatusChartModalHelper, Project) {
            return function(prjs) {
                var deferred = $q.defer();
                var viewState = {
                    'map': 'map',
                    'project': 'project'
                };
                var map = mapInstance.getMap();
                if (map) {
                    map.remove();
                }
                map = new PublicMap('map', {
                    center: [31.1881336, 121.4737701], //上海坐标,默认为地图中心
                    zoom: 13,
                    maxZoom: 18,
                    minZoom: 8,
                    zoomControl: false,
                    doubleClickZoom: false
                });

                map.loadPublicMap(); //加载公共地图,天地图或者高德地图(默认)
                mapInstance.setMap(map, 'map');
                map.addPrjs(prjs); //加载所有项目

                map.on('popupclose', function() {
                    prjStatusChartModalHelper.close();
                });
                map.addEventListener('prjMarkerClick', function(data) {
                    var prj = prjs.filter(function(item) {
                        return item.prjId === data.prjId;
                    })[0];

                    if ($rootScope.curPrj) {
                        $rootScope.curPrj.active = false;
                    }
                    $rootScope.curPrj = prj;
                    $rootScope.curPrj.active = true;

                    toggleSideBar.toggleBottomSideBar('hide').then(function() {
                        //after load project map
                        if (viewMode.monitorType.length === 0) {
                            viewMode.monitorType = prj.monitorPoints[0].monitorType;
                            viewMode.location = prj.monitorPoints[0].locationPoints[0].location;
                        }
                        loadProjectMap(prj);
                    });
                });

                map.on('baselayerchange', function(eventData) {
                    map.mapSource = eventData.name;
                    window.localStorage.setItem('preferMap', eventData.name);
                    // map.addPrjs(Project.prjs);//重新加载marker图层,有点影响效率,先放一边
                });

                map.on('click', function(data) {
                    // console.log(JSON.stringify(data.latlng));
                });

                deferred.resolve(null);
                return deferred.promise;
            };
        }
    ]);
});
